/*
 * @Author: czy
 * @Date: 2021-04-04 22:39:40
 * @LastEditTime: 2021-07-12 22:17:07
 */
#include "stdarg.h"
#include "string.h"
#include "vsprintf.h"

#include "sys/config.h"
#include "sys/system.h"
#include "sys/syscall.h"

static char BUFFER[BUFSIZE];

/**
 * @description: Formats a string in the specified format, and output to standard output device.
 * @param format    Format string.
 * @param args      Parameter list.
 * @return The length of the string in the buffer.
 */
int vprintf(const char *format, va_list args)
{
    int n;
    strzero(BUFFER, BUFSIZE);
    n = vsprintf(BUFFER, format, args);
    _syscall(WRITE, (int)BUFFER, 0);
    return n;
}

/**
 * @description: Formats a string in the specified format, and output to standard output device.
 * @param format    Format string.
 * @return The length of the string in the buffer.
 */
int printf(const char *format, ...)
{
    int n;
    va_list args;
    va_start(args, format);
    n = vprintf(format, args);
    va_end(args);
    return n;
}

/**
 * @description: Get a character from standard input device.
 * @return Character.
 */
int getchar(void)
{
    return _syscall(GETC, 0, 0);
}

/**
 * @description: Output a character to standard output device.
 * @param ch    Character.
 * @return Character.
 */
int putchar(int ch)
{
    return _syscall(PUTC, ch, 0);
}

/**
 * @description: Clear standard output device.
 */
void clear(void)
{
    _syscall(CLS, 0, 0);
}

/**
 * @description: Get a string from standard input device.
 * @param str   String.
 * @return String.
 */
char *gets(char *str)
{
    _syscall(READ, (int)str, 0);
}

/**
 * @description: Output a string to standard output device.
 * @param str   String.
 * @return Number of output characters.
 */
int puts(char *str)
{
    int n = _syscall(WRITE, (int)str, 0);
    _syscall(PUTC, (int)'\n', 0);
    return 0;
}
